<template>
  <div class="space-invaders-container">
    <div class="game-header">
      <h1>🚀 太空入侵者</h1>
      <div class="game-stats">
        <div class="stat-card">
          <div class="stat-label">分数</div>
          <div class="stat-value">{{ score.toLocaleString() }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">波次</div>
          <div class="stat-value">{{ currentWave }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">生命</div>
          <div class="stat-value">{{ lives }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">最高分</div>
          <div class="stat-value">{{ highScore.toLocaleString() }}</div>
        </div>
      </div>
    </div>

    <div class="game-content">
      <!-- 左侧信息面板 -->
      <div class="left-panel">
        <div class="weapon-info">
          <h3>🔫 武器系统</h3>
          <div class="weapon-display">
            <div class="weapon-item" :class="{ active: currentWeapon === 'normal' }">
              <div class="weapon-icon">🔫</div>
              <div class="weapon-name">普通激光</div>
            </div>
            <div class="weapon-item" :class="{ active: currentWeapon === 'spread' }">
              <div class="weapon-icon">💥</div>
              <div class="weapon-name">散射炮</div>
            </div>
            <div class="weapon-item" :class="{ active: currentWeapon === 'laser' }">
              <div class="weapon-icon">⚡</div>
              <div class="weapon-name">激光束</div>
            </div>
          </div>
        </div>

        <div class="powerups-container">
          <h3>🎁 道具效果</h3>
          <div class="active-powerups">
            <div 
              v-for="powerup in activePowerUps"
              :key="powerup.id"
              class="powerup-item"
            >
              <div class="powerup-icon">{{ powerup.icon }}</div>
              <div class="powerup-info">
                <div class="powerup-name">{{ powerup.name }}</div>
                <div class="powerup-timer">{{ Math.ceil(powerup.remaining / 1000) }}s</div>
              </div>
            </div>
          </div>
          <div v-if="activePowerUps.length === 0" class="no-powerups">
            暂无激活道具
          </div>
        </div>

        <div class="controls-info">
          <h3>🎮 操作说明</h3>
          <div class="control-item">
            <span class="key">A/D</span>
            <span class="action">左右移动</span>
          </div>
          <div class="control-item">
            <span class="key">←/→</span>
            <span class="action">左右移动</span>
          </div>
          <div class="control-item">
            <span class="key">空格</span>
            <span class="action">射击</span>
          </div>
          <div class="control-item">
            <span class="key">P</span>
            <span class="action">暂停</span>
          </div>
          <div class="control-item">
            <span class="key">R</span>
            <span class="action">重新开始</span>
          </div>
        </div>
      </div>

      <!-- 游戏主区域 -->
      <div class="game-main">
        <div class="game-controls">
          <button @click="startGame" :disabled="gameRunning" class="control-btn start">
            {{ gameRunning ? '游戏进行中' : '开始游戏' }}
          </button>
          <button @click="pauseGame" :disabled="!gameRunning" class="control-btn pause">
            {{ gamePaused ? '继续' : '暂停' }}
          </button>
          <button @click="resetGame" class="control-btn reset">重新开始</button>
        </div>

        <div class="game-canvas-wrapper">
          <canvas
            ref="gameCanvas"
            :width="canvasWidth"
            :height="canvasHeight"
            class="game-canvas"
            @keydown="handleKeyPress"
            @keyup="handleKeyUp"
            tabindex="0"
          ></canvas>

          <!-- 游戏状态覆盖层 -->
          <div v-if="!gameRunning && !gameOver" class="game-overlay start-overlay">
            <div class="overlay-content">
              <h2>🚀 准备战斗</h2>
              <p>太空入侵者来袭！</p>
              <p>保卫地球，消灭所有入侵者</p>
              <button @click="startGame" class="overlay-btn">开始战斗</button>
            </div>
          </div>

          <div v-if="gamePaused" class="game-overlay pause-overlay">
            <div class="overlay-content">
              <h2>⏸️ 游戏暂停</h2>
              <p>按P键或点击继续按钮恢复游戏</p>
              <button @click="pauseGame" class="overlay-btn">继续战斗</button>
            </div>
          </div>

          <div v-if="gameOver" class="game-overlay game-over-overlay">
            <div class="overlay-content">
              <h2>💀 战斗结束</h2>
              <p>最终分数: <strong>{{ score.toLocaleString() }}</strong></p>
              <p>存活波次: <strong>{{ currentWave }}</strong></p>
              <p v-if="isNewHighScore" class="new-record">🎉 新纪录！</p>
              <button @click="resetGame" class="overlay-btn">重新战斗</button>
            </div>
          </div>

          <div v-if="waveComplete" class="game-overlay wave-complete-overlay">
            <div class="overlay-content">
              <h2>🎊 波次完成！</h2>
              <p>成功击退第 {{ currentWave }} 波入侵者</p>
              <p>获得奖励: <strong>{{ waveBonus.toLocaleString() }}</strong></p>
              <button @click="nextWave" class="overlay-btn">下一波</button>
            </div>
          </div>

          <div v-if="bossMode" class="boss-warning">
            <div class="boss-text">⚠️ BOSS 来袭 ⚠️</div>
          </div>
        </div>
      </div>

      <!-- 右侧信息面板 -->
      <div class="right-panel">
        <div class="enemy-radar">
          <h3>📡 敌人雷达</h3>
          <div class="radar-display">
            <div class="radar-grid">
              <div 
                v-for="enemy in enemies.slice(0, 20)"
                :key="enemy.id"
                class="radar-dot"
                :style="{ 
                  left: (enemy.x / canvasWidth) * 100 + '%',
                  top: (enemy.y / canvasHeight) * 100 + '%',
                  backgroundColor: getEnemyColor(enemy.type)
                }"
              ></div>
            </div>
            <div class="radar-info">
              <div class="enemy-count">敌人数量: {{ enemies.length }}</div>
            </div>
          </div>
        </div>

        <div class="achievements">
          <h3>🏆 成就</h3>
          <div class="achievement-list">
            <div 
              v-for="achievement in achievements"
              :key="achievement.id"
              :class="['achievement', { unlocked: achievement.unlocked }]"
            >
              <div class="achievement-icon">{{ achievement.icon }}</div>
              <div class="achievement-text">
                <div class="achievement-name">{{ achievement.name }}</div>
                <div class="achievement-desc">{{ achievement.description }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="game-tips">
          <h3>💡 战斗提示</h3>
          <div class="tip-list">
            <div class="tip-item">不同敌人有不同的移动模式</div>
            <div class="tip-item">收集道具可以增强火力</div>
            <div class="tip-item">红色敌人血量更高但分数更多</div>
            <div class="tip-item">Boss战需要集中火力攻击</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 粒子效果容器 -->
    <div class="particles-container">
      <div
        v-for="particle in particles"
        :key="particle.id"
        class="particle"
        :style="particle.style"
      ></div>
    </div>

    <!-- 星空背景 -->
    <div class="stars-background">
      <div 
        v-for="star in stars"
        :key="star.id"
        class="star"
        :style="star.style"
      ></div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'

export default {
  name: 'SpaceInvadersGame',
  setup() {
    // 游戏配置
    const canvasWidth = 800
    const canvasHeight = 600
    const playerWidth = 40
    const playerHeight = 30
    const bulletWidth = 4
    const bulletHeight = 10
    const enemyWidth = 30
    const enemyHeight = 25
    
    // 游戏状态
    const gameRunning = ref(false)
    const gamePaused = ref(false)
    const gameOver = ref(false)
    const waveComplete = ref(false)
    const bossMode = ref(false)
    const score = ref(0)
    const currentWave = ref(1)
    const lives = ref(3)
    const highScore = ref(parseInt(localStorage.getItem('spaceInvadersHighScore') || '0'))
    const isNewHighScore = ref(false)
    const waveBonus = ref(0)
    const currentWeapon = ref('normal')
    
    // 游戏对象
    const player = reactive({
      x: canvasWidth / 2 - playerWidth / 2,
      y: canvasHeight - playerHeight - 20,
      width: playerWidth,
      height: playerHeight,
      speed: 6,
      health: 100,
      maxHealth: 100
    })
    
    const bullets = ref([])
    const enemyBullets = ref([])
    const enemies = ref([])
    const powerUps = ref([])
    const activePowerUps = ref([])
    const particles = ref([])
    const stars = ref([])
    
    // 输入状态
    const keys = reactive({
      left: false,
      right: false,
      space: false
    })
    
    // 敌人类型定义
    const enemyTypes = [
      { 
        type: 'basic', 
        color: '#00ff00', 
        points: 10, 
        health: 1, 
        speed: 1,
        shootChance: 0.001,
        icon: '👾'
      },
      { 
        type: 'fast', 
        color: '#ffff00', 
        points: 20, 
        health: 1, 
        speed: 2,
        shootChance: 0.002,
        icon: '🛸'
      },
      { 
        type: 'tank', 
        color: '#ff0000', 
        points: 50, 
        health: 3, 
        speed: 0.5,
        shootChance: 0.003,
        icon: '🚁'
      },
      { 
        type: 'boss', 
        color: '#ff00ff', 
        points: 500, 
        health: 20, 
        speed: 1,
        shootChance: 0.01,
        icon: '👹'
      }
    ]
    
    // 武器类型定义
    const weaponTypes = {
      normal: {
        name: '普通激光',
        damage: 1,
        speed: 8,
        cooldown: 200,
        color: '#00ffff'
      },
      spread: {
        name: '散射炮',
        damage: 1,
        speed: 6,
        cooldown: 300,
        color: '#ff6600',
        spread: true
      },
      laser: {
        name: '激光束',
        damage: 2,
        speed: 12,
        cooldown: 150,
        color: '#ff0066'
      }
    }
    
    // 道具类型定义
    const powerUpTypes = [
      { 
        type: 'health', 
        icon: '❤️', 
        name: '生命恢复', 
        color: '#ff6b6b',
        effect: () => { player.health = Math.min(player.health + 30, player.maxHealth) }
      },
      { 
        type: 'weapon_spread', 
        icon: '💥', 
        name: '散射武器', 
        color: '#ff9500',
        duration: 15000,
        effect: () => { currentWeapon.value = 'spread' }
      },
      { 
        type: 'weapon_laser', 
        icon: '⚡', 
        name: '激光武器', 
        color: '#ff0066',
        duration: 12000,
        effect: () => { currentWeapon.value = 'laser' }
      },
      { 
        type: 'shield', 
        icon: '🛡️', 
        name: '护盾', 
        color: '#4ecdc4',
        duration: 20000,
        effect: () => { player.shield = true }
      },
      { 
        type: 'rapid_fire', 
        icon: '🔥', 
        name: '快速射击', 
        color: '#feca57',
        duration: 10000,
        effect: () => { player.rapidFire = true }
      }
    ]
    
    // 成就系统
    const achievements = ref([
      { id: 1, name: '新兵', description: '击败第一波敌人', icon: '🎯', unlocked: false },
      { id: 2, name: '神射手', description: '连续击中50个敌人', icon: '🎯', unlocked: false },
      { id: 3, name: '生存专家', description: '存活10波', icon: '🛡️', unlocked: false },
      { id: 4, name: 'Boss杀手', description: '击败Boss', icon: '👹', unlocked: false },
      { id: 5, name: '太空英雄', description: '得分超过10000', icon: '🌟', unlocked: false }
    ])
    
    // Canvas 相关
    const gameCanvas = ref(null)
    let ctx = null
    let gameLoop = null
    let lastShot = 0
    let consecutiveHits = 0
    
    // 初始化星空背景
    const initializeStars = () => {
      stars.value = []
      for (let i = 0; i < 100; i++) {
        stars.value.push({
          id: i,
          style: {
            position: 'absolute',
            left: Math.random() * 100 + '%',
            top: Math.random() * 100 + '%',
            width: Math.random() * 3 + 1 + 'px',
            height: Math.random() * 3 + 1 + 'px',
            backgroundColor: 'white',
            borderRadius: '50%',
            opacity: Math.random() * 0.8 + 0.2,
            animation: `twinkle ${Math.random() * 3 + 2}s infinite`
          }
        })
      }
    }
    
    // 初始化敌人
    const initializeEnemies = () => {
      enemies.value = []
      const rows = Math.min(3 + Math.floor(currentWave.value / 3), 6)
      const cols = 8
      
      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
          let enemyType = enemyTypes[0] // 默认基础敌人
          
          // 根据波次和位置决定敌人类型
          if (currentWave.value >= 5 && Math.random() < 0.3) {
            enemyType = enemyTypes[2] // 坦克型
          } else if (currentWave.value >= 3 && Math.random() < 0.4) {
            enemyType = enemyTypes[1] // 快速型
          }
          
          enemies.value.push({
            id: Date.now() + r * cols + c,
            x: c * (enemyWidth + 10) + 50,
            y: r * (enemyHeight + 10) + 50,
            width: enemyWidth,
            height: enemyHeight,
            type: enemyType.type,
            color: enemyType.color,
            points: enemyType.points,
            health: enemyType.health,
            maxHealth: enemyType.health,
            speed: enemyType.speed,
            shootChance: enemyType.shootChance,
            direction: 1,
            lastShot: 0
          })
        }
      }
      
      // Boss战
      if (currentWave.value % 5 === 0) {
        bossMode.value = true
        const bossType = enemyTypes[3]
        enemies.value.push({
          id: Date.now() + 9999,
          x: canvasWidth / 2 - 60,
          y: 50,
          width: 120,
          height: 80,
          type: bossType.type,
          color: bossType.color,
          points: bossType.points,
          health: bossType.health + currentWave.value * 5,
          maxHealth: bossType.health + currentWave.value * 5,
          speed: bossType.speed,
          shootChance: bossType.shootChance,
          direction: 1,
          lastShot: 0,
          isBoss: true
        })
      }
    }
    
    // 获取敌人颜色
    const getEnemyColor = (type) => {
      const enemyType = enemyTypes.find(t => t.type === type)
      return enemyType ? enemyType.color : '#ffffff'
    }
    
    // 绘制游戏
    const draw = () => {
      if (!ctx) return
      
      // 清空画布
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      
      // 绘制太空背景
      const gradient = ctx.createLinearGradient(0, 0, 0, canvasHeight)
      gradient.addColorStop(0, '#000011')
      gradient.addColorStop(0.5, '#000033')
      gradient.addColorStop(1, '#000055')
      ctx.fillStyle = gradient
      ctx.fillRect(0, 0, canvasWidth, canvasHeight)
      
      // 绘制玩家
      ctx.fillStyle = '#00ffff'
      ctx.fillRect(player.x, player.y, player.width, player.height)
      
      // 绘制玩家护盾
      if (player.shield) {
        ctx.strokeStyle = '#4ecdc4'
        ctx.lineWidth = 3
        ctx.beginPath()
        ctx.arc(player.x + player.width / 2, player.y + player.height / 2, player.width, 0, Math.PI * 2)
        ctx.stroke()
      }
      
      // 绘制玩家血条
      const healthBarWidth = 60
      const healthBarHeight = 6
      const healthBarX = player.x + (player.width - healthBarWidth) / 2
      const healthBarY = player.y - 15
      
      ctx.fillStyle = '#ff0000'
      ctx.fillRect(healthBarX, healthBarY, healthBarWidth, healthBarHeight)
      
      ctx.fillStyle = '#00ff00'
      const healthWidth = (player.health / player.maxHealth) * healthBarWidth
      ctx.fillRect(healthBarX, healthBarY, healthWidth, healthBarHeight)
      
      // 绘制敌人
      enemies.value.forEach(enemy => {
        ctx.fillStyle = enemy.color
        ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height)
        
        // 绘制敌人血条（多血量敌人）
        if (enemy.maxHealth > 1) {
          const enemyHealthBarWidth = enemy.width
          const enemyHealthBarHeight = 4
          const enemyHealthBarX = enemy.x
          const enemyHealthBarY = enemy.y - 8
          
          ctx.fillStyle = '#660000'
          ctx.fillRect(enemyHealthBarX, enemyHealthBarY, enemyHealthBarWidth, enemyHealthBarHeight)
          
          ctx.fillStyle = '#ff6666'
          const enemyHealthWidth = (enemy.health / enemy.maxHealth) * enemyHealthBarWidth
          ctx.fillRect(enemyHealthBarX, enemyHealthBarY, enemyHealthWidth, enemyHealthBarHeight)
        }
        
        // Boss特殊效果
        if (enemy.isBoss) {
          ctx.strokeStyle = '#ff00ff'
          ctx.lineWidth = 2
          ctx.strokeRect(enemy.x - 5, enemy.y - 5, enemy.width + 10, enemy.height + 10)
        }
      })
      
      // 绘制子弹
      bullets.value.forEach(bullet => {
        const weapon = weaponTypes[bullet.weapon || 'normal']
        ctx.fillStyle = weapon.color
        ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height)
        
        // 激光武器特效
        if (bullet.weapon === 'laser') {
          ctx.shadowColor = weapon.color
          ctx.shadowBlur = 10
          ctx.fillRect(bullet.x - 1, bullet.y, bullet.width + 2, bullet.height)
          ctx.shadowBlur = 0
        }
      })
      
      // 绘制敌人子弹
      enemyBullets.value.forEach(bullet => {
        ctx.fillStyle = '#ff4444'
        ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height)
      })
      
      // 绘制道具
      powerUps.value.forEach(powerUp => {
        ctx.fillStyle = powerUp.color
        ctx.fillRect(powerUp.x, powerUp.y, powerUp.width, powerUp.height)
        
        ctx.fillStyle = 'white'
        ctx.font = '16px Arial'
        ctx.textAlign = 'center'
        ctx.fillText(powerUp.icon, powerUp.x + powerUp.width / 2, powerUp.y + powerUp.height / 2 + 6)
      })
    }
    
    // 更新游戏状态
    const update = () => {
      if (!gameRunning.value || gamePaused.value) return
      
      // 更新玩家移动
      if (keys.left && player.x > 0) {
        player.x -= player.speed
      }
      if (keys.right && player.x < canvasWidth - player.width) {
        player.x += player.speed
      }
      
      // 更新玩家射击
      if (keys.space) {
        shoot()
      }
      
      // 更新子弹
      bullets.value.forEach((bullet, index) => {
        bullet.y -= bullet.speed
        
        if (bullet.y < 0) {
          bullets.value.splice(index, 1)
        }
      })
      
      // 更新敌人子弹
      enemyBullets.value.forEach((bullet, index) => {
        bullet.y += bullet.speed
        
        if (bullet.y > canvasHeight) {
          enemyBullets.value.splice(index, 1)
        }
        
        // 敌人子弹与玩家碰撞
        if (bullet.x < player.x + player.width &&
            bullet.x + bullet.width > player.x &&
            bullet.y < player.y + player.height &&
            bullet.y + bullet.height > player.y) {
          
          if (!player.shield) {
            player.health -= 20
            if (player.health <= 0) {
              lives.value--
              if (lives.value <= 0) {
                endGame()
              } else {
                respawnPlayer()
              }
            }
          }
          
          enemyBullets.value.splice(index, 1)
          createExplosion(bullet.x, bullet.y, '#ff4444')
        }
      })
      
      // 更新敌人
      let moveDown = false
      enemies.value.forEach(enemy => {
        // 敌人移动
        enemy.x += enemy.speed * enemy.direction
        
        if (enemy.x <= 0 || enemy.x >= canvasWidth - enemy.width) {
          enemy.direction *= -1
          moveDown = true
        }
        
        // 敌人射击
        if (Math.random() < enemy.shootChance) {
          enemyShoot(enemy)
        }
      })
      
      if (moveDown) {
        enemies.value.forEach(enemy => {
          enemy.y += 20
        })
      }
      
      // 子弹与敌人碰撞检测
      bullets.value.forEach((bullet, bulletIndex) => {
        enemies.value.forEach((enemy, enemyIndex) => {
          if (bullet.x < enemy.x + enemy.width &&
              bullet.x + bullet.width > enemy.x &&
              bullet.y < enemy.y + enemy.height &&
              bullet.y + bullet.height > enemy.y) {
            
            const weapon = weaponTypes[bullet.weapon || 'normal']
            enemy.health -= weapon.damage
            
            bullets.value.splice(bulletIndex, 1)
            createExplosion(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2, enemy.color)
            
            if (enemy.health <= 0) {
              score.value += enemy.points
              consecutiveHits++
              
              // 随机生成道具
              if (Math.random() < 0.1) {
                createPowerUp(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2)
              }
              
              enemies.value.splice(enemyIndex, 1)
              
              if (enemy.isBoss) {
                unlockAchievement(3) // Boss杀手
                bossMode.value = false
              }
            }
          }
        })
      })
      
      // 更新道具
      powerUps.value.forEach((powerUp, index) => {
        powerUp.y += powerUp.speed
        
        // 道具与玩家碰撞
        if (powerUp.x < player.x + player.width &&
            powerUp.x + powerUp.width > player.x &&
            powerUp.y < player.y + player.height &&
            powerUp.y + powerUp.height > player.y) {
          
          activatePowerUp(powerUp.type)
          powerUps.value.splice(index, 1)
        }
        
        if (powerUp.y > canvasHeight) {
          powerUps.value.splice(index, 1)
        }
      })
      
      // 更新激活的道具
      activePowerUps.value.forEach((powerUp, index) => {
        powerUp.remaining -= 16
        
        if (powerUp.remaining <= 0) {
          deactivatePowerUp(powerUp.type)
          activePowerUps.value.splice(index, 1)
        }
      })
      
      // 检查波次完成
      if (enemies.value.length === 0) {
        completeWave()
      }
      
      // 检查成就
      checkAchievements()
    }
    
    // 玩家射击
    const shoot = () => {
      const now = Date.now()
      const weapon = weaponTypes[currentWeapon.value]
      const cooldown = player.rapidFire ? weapon.cooldown / 2 : weapon.cooldown
      
      if (now - lastShot < cooldown) return
      
      lastShot = now
      
      if (currentWeapon.value === 'spread') {
        // 散射炮
        for (let i = -1; i <= 1; i++) {
          bullets.value.push({
            x: player.x + player.width / 2 - bulletWidth / 2 + i * 10,
            y: player.y,
            width: bulletWidth,
            height: bulletHeight,
            speed: weapon.speed,
            weapon: currentWeapon.value
          })
        }
      } else {
        // 普通射击
        bullets.value.push({
          x: player.x + player.width / 2 - bulletWidth / 2,
          y: player.y,
          width: bulletWidth,
          height: bulletHeight,
          speed: weapon.speed,
          weapon: currentWeapon.value
        })
      }
    }
    
    // 敌人射击
    const enemyShoot = (enemy) => {
      enemyBullets.value.push({
        x: enemy.x + enemy.width / 2 - bulletWidth / 2,
        y: enemy.y + enemy.height,
        width: bulletWidth,
        height: bulletHeight,
        speed: 3
      })
    }
    
    // 创建道具
    const createPowerUp = (x, y) => {
      const powerUpType = powerUpTypes[Math.floor(Math.random() * powerUpTypes.length)]
      
      powerUps.value.push({
        x: x - 15,
        y: y,
        width: 30,
        height: 20,
        speed: 2,
        type: powerUpType.type,
        icon: powerUpType.icon,
        color: powerUpType.color
      })
    }
    
    // 激活道具
    const activatePowerUp = (type) => {
      const powerUpType = powerUpTypes.find(p => p.type === type)
      if (!powerUpType) return
      
      powerUpType.effect()
      
      if (powerUpType.duration) {
        activePowerUps.value.push({
          id: Date.now(),
          type: type,
          name: powerUpType.name,
          icon: powerUpType.icon,
          remaining: powerUpType.duration
        })
      }
    }
    
    // 取消道具效果
    const deactivatePowerUp = (type) => {
      switch (type) {
        case 'weapon_spread':
        case 'weapon_laser':
          currentWeapon.value = 'normal'
          break
        case 'shield':
          player.shield = false
          break
        case 'rapid_fire':
          player.rapidFire = false
          break
      }
    }
    
    // 创建爆炸效果
    const createExplosion = (x, y, color) => {
      for (let i = 0; i < 12; i++) {
        createParticle(x, y, color)
      }
    }
    
    // 创建粒子
    const createParticle = (x, y, color) => {
      const particle = {
        id: Date.now() + Math.random(),
        style: {
          position: 'absolute',
          left: `${x}px`,
          top: `${y}px`,
          width: '6px',
          height: '6px',
          backgroundColor: color,
          borderRadius: '50%',
          pointerEvents: 'none',
          animation: 'particleExplode 1s ease-out forwards'
        }
      }
      
      particles.value.push(particle)
      
      setTimeout(() => {
        particles.value = particles.value.filter(p => p.id !== particle.id)
      }, 1000)
    }
    
    // 玩家重生
    const respawnPlayer = () => {
      player.x = canvasWidth / 2 - playerWidth / 2
      player.health = player.maxHealth
      player.shield = false
      player.rapidFire = false
      currentWeapon.value = 'normal'
      
      // 清除所有敌人子弹
      enemyBullets.value = []
    }
    
    // 完成波次
    const completeWave = () => {
      waveComplete.value = true
      gameRunning.value = false
      
      waveBonus.value = currentWave.value * 500
      score.value += waveBonus.value
      
      checkAchievements()
    }
    
    // 下一波
    const nextWave = () => {
      currentWave.value++
      waveComplete.value = false
      bossMode.value = false
      
      initializeEnemies()
      
      // 重置道具效果
      activePowerUps.value = []
      powerUps.value = []
      currentWeapon.value = 'normal'
      player.shield = false
      player.rapidFire = false
      
      startGame()
    }
    
    // 检查成就
    const checkAchievements = () => {
      // 新兵：击败第一波敌人
      if (currentWave.value >= 1 && !achievements.value[0].unlocked) {
        unlockAchievement(0)
      }
      
      // 神射手：连续击中50个敌人
      if (consecutiveHits >= 50 && !achievements.value[1].unlocked) {
        unlockAchievement(1)
      }
      
      // 生存专家：存活10波
      if (currentWave.value >= 10 && !achievements.value[2].unlocked) {
        unlockAchievement(2)
      }
      
      // 太空英雄：得分超过10000
      if (score.value >= 10000 && !achievements.value[4].unlocked) {
        unlockAchievement(4)
      }
    }
    
    // 解锁成就
    const unlockAchievement = (index) => {
      achievements.value[index].unlocked = true
      console.log(`成就解锁: ${achievements.value[index].name}`)
    }
    
    // 游戏控制方法
    const startGame = () => {
      if (gameRunning.value) return
      
      gameRunning.value = true
      gamePaused.value = false
      gameOver.value = false
      waveComplete.value = false
      
      if (!enemies.value.length) {
        initializeEnemies()
      }
      
      gameLoop = setInterval(() => {
        update()
        draw()
      }, 16) // 60 FPS
      
      nextTick(() => {
        gameCanvas.value?.focus()
      })
    }
    
    const pauseGame = () => {
      if (!gameRunning.value) return
      
      gamePaused.value = !gamePaused.value
      
      if (gamePaused.value) {
        clearInterval(gameLoop)
      } else {
        gameLoop = setInterval(() => {
          update()
          draw()
        }, 16)
        nextTick(() => {
          gameCanvas.value?.focus()
        })
      }
    }
    
    const resetGame = () => {
      clearInterval(gameLoop)
      
      gameRunning.value = false
      gamePaused.value = false
      gameOver.value = false
      waveComplete.value = false
      bossMode.value = false
      score.value = 0
      currentWave.value = 1
      lives.value = 3
      consecutiveHits = 0
      isNewHighScore.value = false
      
      // 重置游戏对象
      player.x = canvasWidth / 2 - playerWidth / 2
      player.health = player.maxHealth
      player.shield = false
      player.rapidFire = false
      currentWeapon.value = 'normal'
      
      bullets.value = []
      enemyBullets.value = []
      enemies.value = []
      powerUps.value = []
      activePowerUps.value = []
      particles.value = []
      
      // 重置成就
      achievements.value.forEach(achievement => {
        achievement.unlocked = false
      })
      
      initializeEnemies()
      draw()
    }
    
    const endGame = () => {
      clearInterval(gameLoop)
      
      gameRunning.value = false
      gameOver.value = true
      
      // 检查最高分
      if (score.value > highScore.value) {
        highScore.value = score.value
        isNewHighScore.value = true
        localStorage.setItem('spaceInvadersHighScore', score.value.toString())
      }
    }
    
    // 事件处理
    const handleKeyPress = (event) => {
      const key = event.key.toLowerCase()
      
      switch (key) {
        case 'a':
        case 'arrowleft':
          keys.left = true
          break
        case 'd':
        case 'arrowright':
          keys.right = true
          break
        case ' ':
          keys.space = true
          event.preventDefault()
          break
        case 'p':
          pauseGame()
          break
        case 'r':
          resetGame()
          break
      }
    }
    
    const handleKeyUp = (event) => {
      const key = event.key.toLowerCase()
      
      switch (key) {
        case 'a':
        case 'arrowleft':
          keys.left = false
          break
        case 'd':
        case 'arrowright':
          keys.right = false
          break
        case ' ':
          keys.space = false
          break
      }
    }
    
    // 生命周期
    onMounted(() => {
      ctx = gameCanvas.value.getContext('2d')
      initializeStars()
      initializeEnemies()
      draw()
      
      document.addEventListener('keydown', handleKeyPress)
      document.addEventListener('keyup', handleKeyUp)
    })
    
    onUnmounted(() => {
      clearInterval(gameLoop)
      document.removeEventListener('keydown', handleKeyPress)
      document.removeEventListener('keyup', handleKeyUp)
    })
    
    return {
      // 响应式数据
      gameRunning,
      gamePaused,
      gameOver,
      waveComplete,
      bossMode,
      score,
      currentWave,
      lives,
      highScore,
      isNewHighScore,
      waveBonus,
      currentWeapon,
      enemies,
      activePowerUps,
      particles,
      stars,
      achievements,
      gameCanvas,
      canvasWidth,
      canvasHeight,
      
      // 方法
      startGame,
      pauseGame,
      resetGame,
      nextWave,
      handleKeyPress,
      handleKeyUp,
      getEnemyColor
    }
  }
}
</script>

<style scoped>
.space-invaders-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: linear-gradient(135deg, #0c0c0c 0%, #1a1a2e 50%, #16213e 100%);
  min-height: 100vh;
  color: white;
  position: relative;
  overflow: hidden;
}

.stars-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
}

.star {
  position: absolute;
  border-radius: 50%;
}

@keyframes twinkle {
  0%, 100% { opacity: 0.2; }
  50% { opacity: 1; }
}

.game-header {
  text-align: center;
  margin-bottom: 30px;
  position: relative;
  z-index: 1;
}

.game-header h1 {
  font-size: 3em;
  margin-bottom: 20px;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
  background: linear-gradient(45deg, #00ffff, #ff00ff, #ffff00, #00ff00);
  background-size: 400% 400%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  animation: spaceGlow 3s ease infinite;
}

@keyframes spaceGlow {
  0%, 100% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
}

.game-stats {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
}

.stat-card {
  background: rgba(0,255,255,0.1);
  padding: 15px 20px;
  border-radius: 15px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0,255,255,0.3);
  text-align: center;
  min-width: 100px;
  box-shadow: 0 0 20px rgba(0,255,255,0.2);
}

.stat-label {
  font-size: 0.9em;
  opacity: 0.8;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 1.5em;
  font-weight: bold;
  color: #00ffff;
  text-shadow: 0 0 10px #00ffff;
}

.game-content {
  display: grid;
  grid-template-columns: 250px 1fr 250px;
  gap: 30px;
  align-items: start;
  position: relative;
  z-index: 1;
}

.left-panel, .right-panel {
  background: rgba(0,0,0,0.7);
  padding: 20px;
  border-radius: 15px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0,255,255,0.3);
  box-shadow: 0 0 20px rgba(0,255,255,0.1);
}

.weapon-info, .powerups-container, .controls-info {
  margin-bottom: 30px;
}

.weapon-info h3, .powerups-container h3, .controls-info h3 {
  text-align: center;
  margin-bottom: 15px;
  color: #00ffff;
  text-shadow: 0 0 10px #00ffff;
}

.weapon-display {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.weapon-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 8px;
  background: rgba(255,255,255,0.05);
  transition: all 0.3s ease;
}

.weapon-item.active {
  background: rgba(0,255,255,0.2);
  border: 1px solid rgba(0,255,255,0.5);
  box-shadow: 0 0 15px rgba(0,255,255,0.3);
}

.weapon-icon {
  font-size: 1.2em;
  margin-right: 10px;
}

.weapon-name {
  font-size: 0.9em;
  font-weight: bold;
}

.active-powerups {
  max-height: 150px;
  overflow-y: auto;
}

.powerup-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin-bottom: 8px;
  background: rgba(255,255,255,0.1);
  border-radius: 8px;
  border: 1px solid rgba(255,255,255,0.2);
}

.powerup-icon {
  font-size: 1.2em;
  margin-right: 10px;
}

.powerup-info {
  flex: 1;
}

.powerup-name {
  font-size: 0.9em;
  font-weight: bold;
}

.powerup-timer {
  font-size: 0.8em;
  opacity: 0.8;
  color: #ffff00;
}

.no-powerups {
  text-align: center;
  opacity: 0.6;
  font-style: italic;
}

.control-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 0.9em;
}

.control-item .key {
  background: #333;
  color: #00ffff;
  padding: 4px 8px;
  border-radius: 4px;
  font-family: monospace;
  font-weight: bold;
  min-width: 40px;
  text-align: center;
  border: 1px solid #00ffff;
  box-shadow: 0 0 5px rgba(0,255,255,0.3);
}

.game-main {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.game-controls {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.control-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255,255,255,0.2);
  text-transform: uppercase;
}

.control-btn.start {
  background: linear-gradient(45deg, #00ff00, #00cc00);
  color: white;
  box-shadow: 0 0 20px rgba(0,255,0,0.3);
}

.control-btn.pause {
  background: linear-gradient(45deg, #ffaa00, #ff8800);
  color: white;
  box-shadow: 0 0 20px rgba(255,170,0,0.3);
}

.control-btn.reset {
  background: linear-gradient(45deg, #ff0044, #cc0033);
  color: white;
  box-shadow: 0 0 20px rgba(255,0,68,0.3);
}

.control-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 25px rgba(0,0,0,0.3);
}

.control-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.game-canvas-wrapper {
  position: relative;
  border: 3px solid #00ffff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 0 30px rgba(0,255,255,0.5);
}

.game-canvas {
  display: block;
  background: #000011;
  outline: none;
  cursor: crosshair;
}

.game-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(5px);
}

.overlay-content {
  text-align: center;
  background: rgba(0,0,0,0.8);
  padding: 40px;
  border-radius: 20px;
  backdrop-filter: blur(10px);
  border: 2px solid rgba(0,255,255,0.5);
  box-shadow: 0 0 30px rgba(0,255,255,0.3);
}

.overlay-content h2 {
  font-size: 2.5em;
  margin-bottom: 20px;
  color: #00ffff;
  text-shadow: 0 0 20px #00ffff;
}

.overlay-content p {
  font-size: 1.2em;
  margin-bottom: 15px;
  color: #ffffff;
}

.new-record {
  color: #ffff00 !important;
  font-weight: bold;
  font-size: 1.5em !important;
  animation: celebration 1s infinite;
  text-shadow: 0 0 20px #ffff00;
}

@keyframes celebration {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.overlay-btn {
  padding: 15px 30px;
  border: none;
  border-radius: 25px;
  font-size: 18px;
  font-weight: 600;
  background: linear-gradient(45deg, #00ffff, #0099cc);
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 20px;
  text-transform: uppercase;
  box-shadow: 0 0 20px rgba(0,255,255,0.3);
}

.overlay-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 25px rgba(0,255,255,0.5);
}

.boss-warning {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255,0,255,0.9);
  padding: 10px 20px;
  border-radius: 10px;
  border: 2px solid #ff00ff;
  box-shadow: 0 0 20px rgba(255,0,255,0.5);
  z-index: 10;
}

.boss-text {
  font-size: 1.2em;
  font-weight: bold;
  color: white;
  text-shadow: 0 0 10px #ff00ff;
  animation: bossWarning 1s infinite;
}

@keyframes bossWarning {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.enemy-radar {
  margin-bottom: 20px;
}

.enemy-radar h3 {
  text-align: center;
  margin-bottom: 15px;
  color: #00ffff;
  text-shadow: 0 0 10px #00ffff;
}

.radar-display {
  background: rgba(0,0,0,0.8);
  border: 2px solid #00ffff;
  border-radius: 10px;
  padding: 10px;
  position: relative;
}

.radar-grid {
  width: 100%;
  height: 120px;
  position: relative;
  background: radial-gradient(circle at center, rgba(0,255,255,0.1) 0%, transparent 70%);
}

.radar-dot {
  position: absolute;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  animation: radarPulse 2s infinite;
}

@keyframes radarPulse {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.5; transform: scale(1.5); }
}

.radar-info {
  margin-top: 10px;
  text-align: center;
  font-size: 0.9em;
  color: #00ffff;
}

.achievements h3 {
  text-align: center;
  margin-bottom: 15px;
  color: #ffff00;
  text-shadow: 0 0 10px #ffff00;
}

.achievement-list {
  max-height: 200px;
  overflow-y: auto;
}

.achievement {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 8px;
  background: rgba(255,255,255,0.05);
  opacity: 0.5;
  transition: all 0.3s ease;
}

.achievement.unlocked {
  opacity: 1;
  background: rgba(255,255,0,0.2);
  border: 1px solid rgba(255,255,0,0.5);
  box-shadow: 0 0 15px rgba(255,255,0,0.3);
}

.achievement-icon {
  font-size: 1.5em;
  margin-right: 10px;
}

.achievement-text {
  flex: 1;
}

.achievement-name {
  font-weight: bold;
  margin-bottom: 2px;
}

.achievement-desc {
  font-size: 0.8em;
  opacity: 0.8;
}

.game-tips h3 {
  text-align: center;
  margin-bottom: 15px;
  color: #ffff00;
  text-shadow: 0 0 10px #ffff00;
}

.tip-list {
  max-height: 150px;
  overflow-y: auto;
}

.tip-item {
  padding: 8px;
  margin-bottom: 8px;
  background: rgba(255,255,255,0.05);
  border-radius: 6px;
  font-size: 0.9em;
  line-height: 1.4;
  border-left: 3px solid #00ffff;
}

.particles-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1000;
}

.particle {
  position: absolute;
  border-radius: 50%;
}

@keyframes particleExplode {
  to {
    transform: translate(var(--random-x, 0), var(--random-y, 0)) scale(0);
    opacity: 0;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .game-content {
    grid-template-columns: 200px 1fr 200px;
    gap: 20px;
  }
  
  .left-panel, .right-panel {
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .game-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .left-panel, .right-panel {
    order: 2;
  }
  
  .game-main {
    order: 1;
  }
  
  .game-header h1 {
    font-size: 2em;
  }
  
  .game-stats {
    gap: 10px;
  }
  
  .stat-card {
    padding: 10px 15px;
    min-width: 80px;
  }
  
  .game-canvas {
    width: 100%;
    max-width: 400px;
    height: auto;
  }
}
</style>